<template>
  <div class="register-container">
    <div class="register-form">
      <h2 class="title">用户注册</h2>
      
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="form"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            :prefix-icon="Iphone"
          />
        </el-form-item>
        
        <el-form-item label="身份类型" prop="role">
          <el-radio-group v-model="registerForm.role">
            <el-radio :label="0">普通用户</el-radio>
            <el-radio :label="1">服务方</el-radio>
            <el-radio :label="2">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleRegister"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="register-btn"
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
        
        <div class="login-tip">
          已有账号? <el-link type="primary" @click="handleLogin">立即登录</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Iphone, Key } from '@element-plus/icons-vue'
import { register } from '@/util/request'

const router = useRouter()

// 自定义验证规则函数
const validatePassword = (rule, value, callback) => {
  if (value.length < 6) {
    callback(new Error('密码长度不能少于3位'))
  } else if (!/[A-Za-z]/.test(value) || !/[0-9]/.test(value)) {
    callback(new Error('密码必须包含字母和数字'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/
  if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

const validateRole = (rule, value, callback) => {
  if (value === null || value === undefined) {
    callback(new Error('请选择身份类型'))
  } else {
    callback()
  }
}

// 表单引用
const registerFormRef = ref(null)

// 响应式数据
const registerForm = ref({
  username: '',
  phone: '',
  role: null, // 初始为null，用户必须选择
  password: '',
  confirmPassword: '',
})

const registerRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  role: [
    { required: true, validator: validateRole, trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
})

// 验证码相关
const loading = ref(false)

// 方法
const handleRegister = async () => {
  try {
    // 验证表单
    await registerFormRef.value.validate()
    
    loading.value = true
    
    // 构造注册数据
    const registerData = {
      role: registerForm.value.role,
      username: registerForm.value.username,
      password: registerForm.value.password,
      phone: registerForm.value.phone
    }
    const { data } = await register({
      ...registerData
    })
    // console.log("data1.data:",data.data,"data1.code:",data.code)
    if (data.code !== "200") {
      throw new Error(data.message)
    }
    
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    console.log("data:",data.data)
    ElMessage.success('注册成功')
    router.push({
      name: 'login'
    })
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册错误')
    console.error('注册错误:', error)
  } 
}
const handleLogin = () => {
  router.push({
    name: 'login'
  })
}
</script>

<style>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
  background-image: url('~@/assets/login-bg.jpg');
  background-size: cover;
}

.register-form {
  width: 420px;
  padding: 40px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.register-form .title {
  margin-bottom: 30px;
  text-align: center;
  color: #333;
}

.register-form .form .register-btn {
  width: 100%;
  margin-top: 10px;
}

.register-form .login-tip {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-image {
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.el-radio-group {
  width: 100%;
}

.el-radio {
  margin-right: 15px;
}
</style>